package com.project.zsxd.server.calendar.service.impl;

import com.project.zsxd.server.calendar.entity.Calendar;
import com.project.zsxd.server.calendar.mapper.CalendarMapper;
import com.project.zsxd.server.calendar.service.ICalendarService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.project.zsxd.server.common.exception.SystemException;
import com.project.zsxd.server.common.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.project.zsxd.server.common.enums.ResultEnum.ARGUEMENTS_ERROR;
import static com.project.zsxd.server.common.enums.ResultEnum.SYSTEM_ERROR;

/**
 * <p>
 * 日历表 服务实现类
 * </p>
 *
 * @author kaler
 * @since 2021-08-29
 */
@Service
public class CalendarServiceImpl extends ServiceImpl<CalendarMapper, Calendar> implements ICalendarService {

    private static final Logger LOG = LoggerFactory.getLogger(CalendarServiceImpl.class);

    @Override
    public void initData(String startDateText, String endDateText) throws ParseException {
        Date startDate = DateUtil.parseDate(startDateText);
        Date endDate = DateUtil.parseDate(endDateText);
        if (startDate.after(endDate)) {
            LOG.error("startDate must before endDate");
            throw new SystemException(ARGUEMENTS_ERROR);
        }
        Date currDate = (Date) startDate.clone();
        List<Calendar> calendars = new ArrayList<>();
        Calendar calendar;
        while(!currDate.after(endDate)) {
            calendar = new Calendar();
            calendar.setDate(DateUtil.formatDate(currDate));
            calendar.setYear(DateUtil.getYear(currDate));
            calendar.setMonth(DateUtil.getMonth(currDate));
            calendar.setDay(DateUtil.getDay(currDate));
            calendars.add(calendar);
            currDate = DateUtil.calDate(currDate, java.util.Calendar.DAY_OF_MONTH, 1);
        }
        boolean flag = saveOrUpdateBatch(calendars);
        if (!flag) {
            LOG.error("init Data, save Batch error");
            throw new SystemException(SYSTEM_ERROR);
        }
    }
}
